package com.baymax.study.redisson.infrastructure.locks.lock;

import com.baymax.study.redisson.infrastructure.locks.framework.DistributedWriteLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

public class DistributedWriteLockImpl implements DistributedWriteLock {
    private final RedissonClient redissonClient;

    public DistributedWriteLockImpl(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public boolean forceUnlock(String lockName) {
        return redissonClient.getReadWriteLock(lockName).writeLock().forceUnlock();
    }

    @Override
    public boolean isLocked(String lockName) {
        return redissonClient.getReadWriteLock(lockName).writeLock().isLocked();
    }

    @Override
    public void lock(String lockName) {
        redissonClient.getReadWriteLock(lockName).writeLock().lock();
    }

    @Override
    public boolean tryLock(String lockName, Long waitTime, Long leaseTime, TimeUnit unit) {
        try {
            return redissonClient.getReadWriteLock(lockName).writeLock().tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean tryLock(String lockName, Long lockTime, TimeUnit unit) {
        try {
            return redissonClient.getReadWriteLock(lockName).writeLock().tryLock(lockTime, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void unlock(String lockName) {
        redissonClient.getReadWriteLock(lockName).writeLock().unlock();
    }

    @Override
    public boolean isHeldByCurrentThread(String lockName) {
        return redissonClient.getReadWriteLock(lockName).writeLock().isHeldByCurrentThread();
    }
}
